<template>
  <el-dialog title="添加分类" v-model="dialogVisible" width="45%">
    <div class="flex justify-around add-category">
      <div class="category-card-left">
        <ContentWrap class="category-card w-[400px] h-[500px]">
          <el-row>
            <el-col :span="16">
              <!-- 搜索 -->
              <el-input
                v-model="searchQuery"
                placeholder="搜索"
                class="mb-10px"
                :prefix-icon="Search"
                @input="handleSearch"
                clearable
              />
            </el-col>
            <el-col :span="6" class="ml-20px">
              <!-- 是否选全部权限 -->
              <!-- <el-checkbox v-model="filteredSelectedCategories" @change="toggleSelectAll"
                >选择全部权限</el-checkbox
              > -->
            </el-col>
          </el-row>
          <el-row>
            <div class="category-list w-[100%] mt-10px h-[400px] overflow-y-auto">
              <div class="mb-20px"
                ><span>可选属性</span
                ><span class="text-[#999]">（共{{ totalCategories }}个）</span></div
              >
              <!-- 分类树 -->
              <el-tree
                ref="categoryTree"
                :data="categoryData"
                :props="defaultProps"
                node-key="id"
                show-checkbox
                :default-expand-all="true"
                @check="handleCheck"
                :filter-node-method="filterNode"
                v-loading="loading"
                :default-expanded-keys="expandedKeys"
              >
                <template #default="{ node }">
                  <span class="custom-tree-node">{{ node.label }}</span>
                </template>
              </el-tree>
            </div>
          </el-row>
        </ContentWrap>
      </div>
      <div class="category-card-right">
        <ContentWrap class="category-card w-[400px] h-[500px]">
          <el-row>
            <div class="mb-20px"
              ><span>已选属性</span
              ><span class="text-[#999]">（共{{ filteredSelectedCategories.length }}个）</span></div
            >
            <!-- 搜索 -->
            <el-input
              v-model="selectedSearchQuery"
              placeholder="搜索"
              class="mb-20px"
              :prefix-icon="Search"
              @input="filterSelectedCategories"
            />
            <!-- 是否选全部权限 -->
          </el-row>
          <el-row>
            <div class="category-list w-[100%] mt-10px h-[360px] overflow-y-auto">
              <div
                class="flex justify-between category-item mb-20px"
                v-for="(item, index) in filteredSelectedCategories"
                :key="index"
              >
                <div class="flex items-center category-item-left">
                  <Icon
                    icon="fluent:re-order-dots-vertical-16-regular"
                    class="mr-2px text-[#999]"
                  />
                  <span class="inline-block w-[280px] truncate">{{ item.name }} </span>
                </div>
                <div class="category-item-right">
                  <Icon icon="ep:close" @click="handleRemoveCategory" class="font-semibold" />
                </div>
              </div>
            </div>
          </el-row>
        </ContentWrap>
      </div>
    </div>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="handleConfirm">确 定</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { Calendar, Search } from '@element-plus/icons-vue'
import { WebSiteApi, WebSiteVO } from '@/api/website/website'
import { defaultProps, handleTree } from '@/utils/tree'

const emit = defineEmits(['close', 'confirm'])
const props = defineProps(['classificationList', 'isAddCategory'])
// 存储需要展开的节点 keys
const expandedKeys = ref([])
const categoryData = ref()
const totalCategories = ref(0)
const dialogVisible = ref(true)
const searchQuery = ref('')
const filteredSelectedCategories = ref<Array<{ id: string | number; name: string }>>([])
const selectedSearchQuery = ref('')
const selectedCategories = ref<Array<{ id: string | number; name: string }>>([])
const categoryTree = ref<InstanceType<typeof ElTree>>()
const loading = ref(false)
// 全选/取消全选

const toggleSelectAll = () => {
  if (categoryTree.value) {
    if (filteredSelectedCategories.value) {
      // 获取所有叶子节点ID
      const allLeafIds = getAllLeafIds(categoryData.value)
      categoryTree.value.setCheckedKeys(allLeafIds)
    } else {
      categoryTree.value.setCheckedKeys([])
      selectedCategories.value = []
      filteredSelectedCategories.value = []
    }
  }
}
// 自定义过滤方法
const filterNode = (value, data) => {
  if (!value) return true
  return data.name.includes(value)
}
// 方法
const handleSearch = (value) => {
  console.log(value)
  if (categoryTree.value) {
    categoryTree.value.filter(value)

    if (value) {
      expandedKeys.value = findMatchingKeys(categoryData.value, value)
    } else {
      expandedKeys.value = [] // 清空搜索时收起所有节点
    }
  }
}
// 递归查找匹配的节点 keys
const findMatchingKeys = (nodes, keyword, keys = []) => {
  nodes?.forEach((node) => {
    if (node.name.includes(keyword)) {
      keys.push(node.id)
    }
    if (node.children) {
      findMatchingKeys(node.children, keyword, keys)
    }
  })
  return keys
}
// 获取所有叶子节点ID
const getAllLeafIds = (nodes: any[]): any[] => {
  let ids: any[] = []
  nodes.forEach((node) => {
    if (!node.children || node.children.length === 0) {
      ids.push(node.id)
    } else {
      ids = ids.concat(getAllLeafIds(node.children))
    }
  })
  return ids
}
// 分页查询导航关联分类
const handleNavigationCategoryPage = async () => {
  // await WebSiteApi.getWebNavigationCategoryList().then((res) => {
  //   categoryData.value = handleTree(res)
  // })
  loading.value = true
  try {
    const res = await WebSiteApi.getWebNavigationCategoryList()
    categoryData.value = handleTree(res)
    // 计算总分类数（只计算叶子节点）
    totalCategories.value = countLeafNodes(categoryData.value)
  } catch (error) {
    console.error('获取分类数据失败:', error)
  }
  loading.value = false
}

const getAllKeys = (nodes) => {
  let keys = []
  nodes.forEach((node) => {
    keys.push(node.id)
    if (node.children && node.children.length > 0) {
      keys = keys.concat(getAllKeys(node.children))
    }
  })
  return keys
}
// 移除已选分类
const handleRemoveCategory = (id: string | number) => {
  // 从已选列表中移除
  selectedCategories.value = selectedCategories.value.filter((item) => item.id !== id)

  // 更新树的选择状态
  updateTreeCheckedNodes()

  // 更新过滤后的已选列表
  filterSelectedCategories()
}
// 更新树的选择状态
const updateTreeCheckedNodes = () => {
  if (categoryTree.value) {
    const selectedIds = selectedCategories.value.map((item) => item.id)
    categoryTree.value.setCheckedKeys(selectedIds)
  }
}
// 过滤已选分类
const filterSelectedCategories = () => {
  if (!selectedSearchQuery.value) {
    filteredSelectedCategories.value = [...selectedCategories.value]
  } else {
    filteredSelectedCategories.value = selectedCategories.value.filter((item) =>
      item.name.includes(selectedSearchQuery.value)
    )
  }
}
// 计算叶子节点数量
const countLeafNodes = (nodes: any[]): number => {
  let count = 0
  nodes.forEach((node) => {
    if (!node.children || node.children.length === 0) {
      count++
    } else {
      count += countLeafNodes(node.children)
    }
  })
  return count
}
// 确认选择
const handleConfirm = () => {
  emit('confirm', selectedCategories.value)
  dialogVisible.value = false
}
// 选择
const handleCheck = (data: any, { checkedNodes }: any) => {
  // 只保留叶子节点
  const leafNodes = checkedNodes.filter((node: any) => !node.children || node.children.length === 0)

  // 转换为需要的格式
  selectedCategories.value = leafNodes.map((node: any) => ({
    id: node.id,
    name: node.name,
    productCount: node.productCount
  }))

  // 更新过滤后的已选列表
  filterSelectedCategories()
}
watch(dialogVisible, (val) => {
  if (!val) {
    emit('close')
  }
})
watch(
  () => props.isAddCategory,
  (val) => {
    dialogVisible.value = val
  }
)
onMounted(() => {
  handleNavigationCategoryPage()
  // 如果有传入已选分类列表，设置选中状态
  if (props.classificationList && props.classificationList.length > 0) {
    // 转换格式并设置到 selectedCategories
    selectedCategories.value = props.classificationList.map((item) => ({
      id: item.id,
      name: item.name
    }))
  }
  // 更新过滤后的已选列表
  filterSelectedCategories()
  // 等待树渲染完成后设置选中状态
  nextTick(() => {
    if (categoryTree.value) {
      // 只设置叶子节点的选中状态
      const selectedIds = props.classificationList.map((item) => item.id)
      categoryTree.value.setCheckedKeys(selectedIds)
    }
  })
  console.log('props.classificationList', props.classificationList)
  console.log('filteredSelectedCategories.value', filteredSelectedCategories.value)
})
</script>

<style scoped></style>
